#!/bin/bash
source ./config.sh
source ./logging.sh
source ./converthl.sh
source ./glue.sh

FILES=""

log "New Converting Process started."
#hl_and_convert main.c code.html

rm -rf $HTML_DIRECTORY
if ! [ -d $HTML_DIRECTORY ]; then
	log "Creating $HTML_DIRECTORY"
	mkdir $HTML_DIRECTORY
else
	log "Please remove $HTML_DIRECTORY."
	exit 1
fi

# convert all the code.
#for x in $(ls $RESOURCE_PATH/code); do
#	log "converting $x to [SYNTAX HTML]"
#	hl_and_convert $RESOURCE_PATH/code/$x \
#		$RESOURCE_PATH/HTML/$(echo $x | cut -f1 -d.).html
#done

build_tags() {
	# build all the tag files.
	FILES="$(ls $RESOURCE_PATH)"
	for x in $FILES; do
		create_temp $PREFAB_PATH/$1 ${TEMP_PATH}/$x $x
	done
}

#Usage: glue_tag <filename> <tagname>
glue_tag() {
	if [ -z $(echo "$FILES" | sed -n "/$2/p") ]; then
		echo "Already glued that."
		exit
	fi

	log "Glueing $1: $2"
	glue "$HTML_DIRECTORY/$1" "$HTML_DIRECTORY/$1" $TEMP_PATH/$2 $2
	rm ${TEMP_PATH}/$2
	FILES="$(ls $TEMP_PATH)"
}

build_tags index.pfb
# Treat HLCODE special.
FILES=$(echo "$FILES" | sed 's/HLCODE//')

cp $PREFAB_PATH/index.pfb $HTML_DIRECTORY/index.html
for i in $FILES; do
	glue_tag index.html $i
done
rm -rf $TEMP_PATH/*


build_tags linux_on_mac.pfb
# Treat HLCODE special.
FILES=$(echo "$FILES" | sed 's/HLCODE//')

cp $PREFAB_PATH/linux_on_mac.pfb $HTML_DIRECTORY/linux_on_mac.html
for i in $FILES; do
	glue_tag linux_on_mac.html $i
done

build_tags interesting_stuff.pfb
# Treat HLCODE special.
FILES=$(echo "$FILES" | sed 's/HLCODE//')

cp $PREFAB_PATH/interesting_stuff.pfb $HTML_DIRECTORY/interesting_stuff.html
for i in $FILES; do
	glue_tag interesting_stuff.html $i
done

build_tags download_stuff.pfb
# Treat HLCODE special.
FILES=$(echo "$FILES" | sed 's/HLCODE//')

cp $PREFAB_PATH/download_stuff.pfb $HTML_DIRECTORY/download_stuff.html
for i in $FILES; do
	glue_tag download_stuff.html $i
done
#glue "$HTML_DIRECTORY/index.html" "$HTML_DIRECTORY/index.html" $TEMP_PATH TEXT


log "Linking CSS into website."
#ln -s $PREFAB_PATH/style $HTML_DIRECTORY/css
cp -r $PREFAB_PATH/style $HTML_DIRECTORY/css

log "Creating Site archive..."
tar -I pxz -cvf $HTML_DIRECTORY/site.tar.xz $HTML_DIRECTORY

log "Creating Script archive..."
tar -I pxz -cvf $HTML_DIRECTORY/scripts.tar.xz $(pwd)

#rm $TEMP_PATH
log "End of Converting Process."
